#include "List.h"

ListNode* ListInit()
{
	ListNode* ret = (ListNode*)malloc(sizeof(ListNode));
	if (ret == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	ret->prev = ret;
	ret->next = ret;
	ret->val = -1;
	return ret;
}



void ListPrint(ListNode* phead)
{
	assert(phead);
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("\n");
}

void ListDestroy(ListNode* phead)
{
	if (phead->next == NULL)
	{
		free(phead);
		return;
	}
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		ListNode* pnext = pcur->next;
		free(pcur);
		pcur = pnext;
	}
}

ListNode* BuyNode(ListDataType x)
{
	ListNode* ret = (ListNode*)malloc(sizeof(ListNode));
	if (ret == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	ret->prev = ret;
	ret->next = ret;
	ret->val = x;
	return ret;
}


void ListPushFront(ListNode* phead, ListDataType x)
{
	assert(phead);
	ListNode* newnode = BuyNode(x);

	newnode->next = phead->next;
	phead->next->prev = newnode;
	
	newnode->prev = phead;
	phead->next = newnode;
}


void ListPopFront(ListNode* phead)
{
	assert(phead->next!=phead);

	ListNode* del = phead->next;
	del->next->prev = phead;

	phead->next = del->next;
	free(del);

}
void ListPushBack(ListNode* phead, ListDataType x)
{
	assert(phead);
	ListNode* newnode = BuyNode(x);

	phead->prev->next = newnode;
	newnode->prev = phead->prev;

	newnode->next = phead;
	phead->prev = newnode;

}
void ListPopBack(ListNode* phead)
{
	assert(phead->next != phead);
	ListNode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
}

ListNode* ListFind(ListNode* phead,ListDataType x)
{
	assert(phead);
	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->val == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}
void ListInsert(ListNode* pos, ListDataType x)
{
	ListNode* newnode = BuyNode(x);
	pos->next->prev = newnode;
	newnode->next = pos->next;

	newnode->prev = pos;
	pos->next = newnode;
}
void ListErase(ListNode* pos)
{
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
}


bool ListEmpty(ListNode* phead)
{
	return phead->next == phead;
}